import {Component, ComponentFactoryResolver, Input, QueryList, ViewChildren, ViewContainerRef} from '@angular/core';
import {CommonPage} from '../../common-page';
import {ObjectUtil} from '../../../../shared/utils/object-util';
import {ChildFormComponent} from '../child/child.form.component';

@Component({
  templateUrl: './dictionary.form.component.html'
})
export class DictionaryFormComponent extends CommonPage {

  inputList = [];
  @Input() id;
  @Input() name;
  @Input() email;
  @Input() code;
  @Input() projectId;

  @ViewChildren('inputTemplate', {read: ViewContainerRef}) templateList: QueryList<ViewContainerRef>;

  constructor(private componentFactoryResolver: ComponentFactoryResolver) {
    super();
  }


  @Input() set children(values) {
    if (!ObjectUtil.isHaveValue(values)) {
      this.inputList = [];
      return;
    }
    const inputs = [];
    for (let i = 0; i < values.length; i++) {
      inputs.push({index: i});
    }
    this.inputList = inputs;

    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(ChildFormComponent);
    setTimeout(() => {
      for (let i = 0; i < this.inputList.length; i++) {
        const viewRef = this.templateList.filter((p, j) => j == i)[0];
        const instance = viewRef.createComponent(componentFactory).instance;
        instance['name'] = values[i].name;
        instance['code'] = values[i].code;
        instance['id'] = values[i].id;
      }
    }, 50);
  }


  reduce({index: k}) {
    let n = 0;
    this.inputList.forEach(({index}, j) => {
      if (k == index) {
        n = j;
      }
    })
    this.inputList.splice(n, 1);
  }

  plus() {

    const lastIndex = this.inputList.length > 0 ? this.inputList[this.inputList.length - 1].index : -1;
    this.inputList.push({index: lastIndex + 1});
    setTimeout(() => {
      const componentFactory = this.componentFactoryResolver.resolveComponentFactory(ChildFormComponent);
      const viewRef = this.templateList.filter((p, j) => j == this.templateList.length - 1)[0];
      viewRef.clear();
      const instance1 = viewRef.createComponent(componentFactory).instance;
    }, 100);
  }


}




